package just.stuff.morsels.ui.user;

import java.util.ArrayList;
import java.util.List;

import just.stuff.morsels.MorselApplication;
import just.stuff.morsels.MorselSession;
import just.stuff.morsels.objects.Morsel;
import just.stuff.morsels.objects.User;
import just.stuff.morsels.ui.BasePage;
import just.stuff.morsels.ui.label.LabelPage;
import just.stuff.morsels.ui.morsel.MorselList;
import just.stuff.morsels.util.TextLink;

import org.apache.wicket.PageParameters;
import org.apache.wicket.RedirectToUrlException;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.Model;

public class UserPage extends BasePage {

	public UserPage() {
		final User user = getCurrentUser();
		add( new Label( "name", user.getEmail() ) );
		List<Morsel> morsels = MorselApplication.dataSource().morselsWithAssistance( user );
		add( new MorselList( "morsels", Model.ofList( morsels )) );
		add( new ListView<String>( "assistance", new ArrayList<String>( user.getAssistanceSubscriptions() ) ) {
			@Override
			protected void populateItem(ListItem<String> item) {
				PageParameters pp = new PageParameters();
				pp.put( LabelPage.PARAM_LABEL, item.getModelObject() );
				item.add( new TextLink<String>( "label" , LabelPage.class, pp, Model.of( item.getModelObject() ) ) );
				List<Morsel> morsels = MorselApplication.dataSource().morselsWithAssistance( item.getModelObject() );
				item.add( new MorselList( "morsels", Model.ofList( morsels )) );
				
			}
		});
	}

	public User getCurrentUser() {
		final User user = MorselSession.get().getUser();
		if( user == null )
			throw new RedirectToUrlException( "/" );
		return user;
	}
	
	@Override
	protected void onBeforeRender() {
		getCurrentUser();
		super.onBeforeRender();
	}
	
}
